package crmdna.client.user;

import java.util.List;

import javax.inject.Named;

import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.config.ApiMethod.HttpMethod;
import com.google.appengine.api.users.User;

import crmdna.client.user.User.Action;
import crmdna.client.user.User.ResourceType;
import crmdna.client.user.UserCore.UserProp;
import crmdna.common.APIResponse;
import crmdna.common.APIResponse.Status;
import crmdna.common.Utils;

@Api(name = "user")
public class UserApi {
	@ApiMethod(path="create", httpMethod = HttpMethod.POST)
	public APIResponse create(@Named("client") String client, 
			@Named("email") String email, @Named("group_id") long groupId,  
			User user) {
		
		try {			
			UserProp prop = crmdna.client.user.User.create(client, email, groupId, Utils.getLoginEmail(user));
								
			return new APIResponse(Status.SUCCESS, prop);
			
		} catch (Exception ex) {
			return new APIResponse(ex);
		}		
	}
	
	@ApiMethod(path="addOrDeletePrivilege", httpMethod = HttpMethod.POST)
	public APIResponse addOrDeletePrivilege(@Named("client") String client, 
			@Named("email") String email, 
			@Named("resource_type") ResourceType resourceType, 
			@Named("resource_id") long resourceId,
			@Named("action") Action action,
			@Named("add") Boolean add, 
			User user) {
		
		try {
			
			UserProp prop = crmdna.client.user.User.addOrDeletePrivilege(client, email, resourceType, 
					resourceId, action, add, Utils.getLoginEmail(user));
								
			return new APIResponse(Status.SUCCESS, prop);
			
		} catch (Exception ex) {
			return new APIResponse(ex);
		}		
	}
	
	@ApiMethod(path="getAll", httpMethod = HttpMethod.GET)
	public APIResponse getAll(@Named("client") String client) {
		
		try {			
			List<UserProp> props = crmdna.client.user.User.getAll(client);
								
			return new APIResponse(Status.SUCCESS, props);
			
		} catch (Exception ex) {
			return new APIResponse(ex);
		}		
	}
	
	@ApiMethod(path="getLoggedInUser", httpMethod = HttpMethod.GET)
	public APIResponse getLoggedInUser(User user) {
		
		try {	
			String result = Utils.getLoginEmail(user);

			if (null == result)
				result = "not logged in";
								
			return new APIResponse(Status.SUCCESS, result);
			
		} catch (Exception ex) {
			return new APIResponse(ex);
		}		
	}
}
